package com.example.job.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.enums.ExamListType;
import com.example.common.redis.RedisService;
import com.example.job.domain.Exam;
import com.example.job.mapper.ExamMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 23050
 * @version 1.0
 * @description: xxl-job 定时任务handler类
 * @date 2025/3/9 21:33
 */
@Component
public class ExamXxlJob {

    @Resource
    private ExamMapper examMapper;

    @Resource
    private RedisService redisService;

    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler(){

        //统计那些竞赛应该存入未完赛的列表，那些竞赛应该存入历史竞赛列表
        List<Exam> unFinishList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .gt(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, 1)
                .orderByDesc(Exam::getStartTime));
        System.out.println("---------------刷新未完成list");
        //刷新未完成的redis
        refreshCache(unFinishList,CacheConstants.EXAM_UNFINISHED_LIST);

        List<Exam> historyList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .le(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, 1)
                .orderByDesc(Exam::getStartTime));
        System.out.println("-------------- 刷新历史list");
        //刷新历史竞赛的redis
        refreshCache(historyList,CacheConstants.EXAM_HISTORY_LIST);

    }

    //刷新redis
    public void refreshCache(List<Exam> examList,String examListKey) {

        if (CollectionUtil.isEmpty(examList)){
            return;
        }
        //将拿到的数据放到redis中
        Map<String, Exam> examMap = new HashMap<>();  //exam:detail:examId - exam详情
        List<Long> examIdList = new ArrayList<>();  //用于刷新未完赛和历史竞赛的数据
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        //批量的将竞赛详情存到redis中 exam:detail:examId:竞赛详情
        redisService.multiSet(examMap);  //刷新详情缓存
        //删除未完赛或历史竞赛列表  然后重新存储
        redisService.deleteObject(examListKey);
        //刷新列表缓存
        redisService.rightPushAll(examListKey, examIdList);
    }


    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }









}
